package com.davidlife.framework.mybatis.annotation.dao;

import com.davidlife.framework.mybatis.annotation.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;

import java.util.List;

public interface UserDao {

    /**
     * 查询所有用户
     */
    @Select("select * from user")
    //当数据库返回的列名与实体类字段名不一致时怎么map：
    /*@Results(id="userMap",value={       //这里指定id="userMap"，然后别的地方就可以直接用了：@ResultMap("userMap")
            @Result(id=true,column = "id",property = "userId"),
            @Result(column = "username",property = "userName"),
            @Result(column = "address",property = "userAddress"),
            @Result(column = "sex",property = "userSex"),
            @Result(column = "birthday",property = "userBirthday"),
            @Result(property = "accounts",column = "id",
                    many = @Many(select = "com.itheima.dao.IAccountDao.findAccountByUid",
                            fetchType = FetchType.LAZY))
    })*/
    @Results(id = "userMap", value = {
            @Result(id = true, property = "id", column = "id"),  //注意：发现这里不写id的result的话，返回的User对象中id为null，而别的字段也没写，就都有值，不知为啥。。。
            @Result(property = "accounts", column = "id",
                    many = @Many(select = "com.davidlife.framework.mybatis.annotation.dao.AccountDao.findAccountByUid",
                            fetchType = FetchType.LAZY))
    })
    List<User> findAll();

    /**
     * 保存用户
     *
     * @param user
     */
    @Insert("insert into user (username, sex, address, birthday) values (#{username}, #{sex}, #{address}, #{birthday})")
    void saveUser(User user);

    /**
     * 更新用户
     *
     * @param user
     */
    @Update("update user set username=#{username},sex=#{sex},birthday=#{birthday},address=#{address} where id=#{id}")
    void updateUser(User user);

    /**
     * 删除用户
     *
     * @param userId
     */
    @Delete("delete from user where id=#{id} ")
    void deleteUser(Integer userId);

    /**
     * 根据id查询用户
     *
     * @param userId
     * @return
     */
    @Select("select * from user  where id=#{id} ")
    /*@ResultMap("userMap") //这里写全了是这样：@ResultMap(value={"userMap"})*/
    User findById(Integer userId);

    /**
     * 根据用户名称模糊查询
     *
     * @param username
     * @return
     */
    @Select("select * from user where username like #{username} ")
//    @Select("select * from user where username like '%${value}%' ")
    List<User> findUserByName(String username);

    /**
     * 查询总用户数量
     *
     * @return
     */
    @Select("select count(*) from user ")
    int findTotalUser();
}
